package com.wu.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.wu.store.dao.UserDao;
import com.wu.store.entity.User;
import com.wu.store.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

	@Value("${session.timeout}")
	private String timeout;

	@Autowired
	private UserDao userDao;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	public User getUserInfo(Long uid) throws Exception {
		if (uid == null) {
			throw new Exception("用户id必需");
		}
		User user = userDao.getUserByUid(uid);
		if (user == null) {
			throw new Exception("用户未注册");
		}
		return user;
	}

	@Override
	public void updateUserCache(User user) {
		Subject currentSubject = SecurityUtils.getSubject();
		Session session = currentSubject.getSession();
		String sessionId = (String) session.getId();
		ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
		stringStringValueOperations.set(sessionId, JSON.toJSONString(user), Integer.parseInt(timeout), TimeUnit.MILLISECONDS);
	}

	public boolean validateIsUsernameValid(String username, User targetUser) throws Exception {
		if (StringUtils.isEmpty(username)) {
			throw new Exception("username必需");
		}

		User user = userDao.getUserByUserName(username);
		if (targetUser == null) {
			targetUser = new User();
		}
		if (user != null && !user.getId().equals(targetUser.getId())) {
			throw new Exception("用户名已被占用");
		}
		return true;
	}
}
